import getopt
import sys
import httplib
import getpass
import base64
from caldavclientlibrary.protocol.webdav.definitions import davxml
from caldavclientlibrary.protocol.url import URL
from caldavclientlibrary.protocol.webdav.definitions import davxml

class Request():
	def __init__(self, url=None, method=None):
		self.Uurl = url
		self.method = method
		self.body = None
		self.headers = {}
	def add_auth(self, user, pswd):
		bstr = base64.encodestring('%s:%s' % (user, pswd))[:-1]
		authheader = "Basic %s" % bstr
		self.headers["Authorization"] = authheader
	def add_header(self, key, val):
		self.headers[key] = val
	def add_body(self, body):
		self.body = body
	def send(self):
		conn = httplib.HTTPSConnection(self.Uurl.server)
		if not self.body:
			conn.request(self.method, self.Uurl.relativeURL(), headers=self.headers) 
		else:
			conn.putrequest(self.method, self.Uurl.relativeURL(), skip_accept_encoding=True)
			for k in self.headers.keys():
				conn.putheader(k, self.headers[k])
			conn.endheaders()
			conn.send(self.body)
		response = conn.getresponse()
		print response.read()

class CaldavConnection():
	def __init__(self, username, password, url):
		if url.startswith("http"):
			self.Uurl = URL(url)
		else:
			print "Please supply a url beginning with http..."
			sys.exit()
		self.user = username
		self.passwd = password
	def request_prop(self):
		req = Request(self.Uurl, "PROPFIND")
		req.add_auth(self.user, self.passwd)
		req.add_header("Depth",1)
		#req.add_body(davxml.resourcetype.text)
		#print "adding body: " + davxml.resourcetype.text
		req.send()


def run( username, password, url):
	#Create headers
	caldav = CaldavConnection(username, password, url)
	caldav.request_prop()


if __name__ == "__main__":
	options, args = getopt.getopt(sys.argv[1:], "", ["user=","passwd=","url="])
	options = dict(options)
	if not "--url" in options:
		options["--url"] = raw_input("Enter url (include http:..) ")
	if not "--user" in options:
		options["--user"] = raw_input("Enter user name: ")
	if not "--passwd" in options:
		options["--passwd"] = getpass.getpass()
	run(options["--user"], options["--passwd"], options["--url"])
